import { QUALITY_SIZE, CODE_PUSH_DEPLOYMENT_KEY } from './../../../providers/Config';
import { Component, Injector, ElementRef, ViewChildren, QueryList } from '@angular/core';
import { IonicPage, NavController, Content } from 'ionic-angular';

import { BasePage } from "../../basePage";
import { UserService } from '../../../providers/UserService';
import { StorageService } from '../../../providers/StorageService';
import { PIC_URL } from "../../../providers/Config";

declare var $: any
/**
 * Generated class for the BuycarPage page.
 *
 * See https://ionicframework.com/docs/components/#navigation for more info on
 * Ionic pages and navigation.
 */

@IonicPage()
@Component({
  selector: 'page-buycar',
  templateUrl: 'buycar.html',
})
export class BuycarPage extends BasePage {
  toHome: boolean;
  choiceWay: boolean;
  num: any;
  goodsID = [];
  selectAllArr = [];

  /*表示全选按钮是否被选中 默认是没有被选中*/
  showSelectImg: boolean = false;
  isSelectImg: string;
  selectAll: boolean;
  shopID: any;
  @ViewChildren("buycarContainer") content: Content;
  cateItemDiv: ElementRef;
  _elementRef: any;

  happy = "daodian"
  picrooturl = "";//图片服务地址
  userinfo = {};
  Buycarlist = [];
  a = false;   //控制管理和完成显示
  activation = false;  //激活图片删除（控制未选中样式）
  activation2 = false;   //控制结算显示
  activationn = false;    //控制选中样式
  change = true;    //控制编辑显示
  blank: boolean  //控制购物车为空时
  //获取购物车参数
  param = {
    user_id: 0
  };
  //删除购物车参数
  param2 = {
    user_id: null,
    item_ids: ""
  }
  //修改购物车数量参数
  param3 = {
    user_id: 0,
    cart_id: 0,
    goods_num: 0
  }
  total = 0;
  sellTotle = null;
  alltotal: number


  constructor(injector: Injector, public userService: UserService, public stc: StorageService, private elementRef: ElementRef) {
    super(injector);
    this.picrooturl = PIC_URL
    this.userinfo = this.stc.read('userinfo');
    console.log(this.userinfo);
    this.getmybuycar();
    this.countAll();

  }

  //每次调用
  ionViewDidLoad() {
    this.userinfo = this.stc.read('userinfo');
  }

  // ionViewDidEnter() {
  //     let stxt = document.querySelector(".imgcoll");
  //     console.log(stxt)

  // }


  /*获取用户购物车列表*/
  async getmybuycar() {
    
    this.param.user_id = this.userinfo['user_id'];
    let result = await this.userService.getMyCartListAPI(this.param);
    
    console.log(result);
    
    this.Buycarlist = result.data.list;
    if (this.Buycarlist.length > 0) {
      /*表示购物车不为空*/
      this.blank = false;

      for (let i = 0; i < this.Buycarlist.length; i++) {
        this.Buycarlist[i]['select'] = false;
        this.Buycarlist[i]['selectimg'] = "assets/img/selectno1.png";

        let goods_num = this.Buycarlist[i].goods_info.length;
        for (let j = 0; j < goods_num; j++) {
          this.Buycarlist[i]['goods_info'][j]['selectimg'] = 'assets/img/selectno1.png';
          this.Buycarlist[i]['goods_info'][j]['select'] = false;
        }
      }
    } else if (this.Buycarlist.length == 0) {
      this.blank = true;
    }
    this.sellTotle = this.Buycarlist.length;
    console.log(this.Buycarlist)
    this.countAll();
  }

  /*计算所有的总价*/
  countAll() {
    this.total = 0;
    this.num = 0;
    for (var i = 0,length = this.Buycarlist.length; i < length; i++) {
      for (var j = 0,goodsLength = this.Buycarlist[i].goods_info.length; j < goodsLength; j++) {
        if(this.Buycarlist[i].goods_info[j].select){
          /*被选中的商品*/
          this.total += this.Buycarlist[i].goods_info[j].goods_num * this.Buycarlist[i].goods_info[j].service_info.service_price;          
          this.num += this.Buycarlist[i].goods_info[j].goods_num;
        }
      }
    }
  }


  /**点击启动删除图标 */
  activationokCLI() {
    this.a = false;
    this.activation = false;//
    this.activation2 = false;//删除按钮
    this.activationn = false;
    this.selectAll = false;
  }
  /**点击关闭删除小图标 */
  activationCLI() {
    this.a = true;
    this.activation = true;
    this.activation2 = true;
    this.activationn = false;
    this.selectAll = true;
    this.showSelectImg = false;/**全选图标 */
    // this.selectCLI(null)
  }


  /*
    将一个店铺里面的所有服务都选中
    通过传入 当前店铺在 Buycarlist 中的位置 以及当前店铺的select状态
    来改变 里面的select状态  
  */
  selectAllByIndex({ shop_index, isTrue = this.Buycarlist[shop_index]["select"] }) {
    // isTrue = isTrue || this.Buycarlist[shop_index]["select"];

    /*
     isTrue 默认指为当前商品的选中状态，如果没有被选中，则被选中
      特殊情况要手动改变当前店铺的商品的状态 则要传第二个参数
    */
    let imgUrl;
    if (isTrue) imgUrl = "assets/img/selectno1.png";
    else imgUrl = "assets/img/selectok.png";

    this.Buycarlist[shop_index]["select"] = !isTrue;
    this.Buycarlist[shop_index]["selectimg"] = imgUrl;
    let goodsLength = this.Buycarlist[shop_index]['goods_info'].length;
    for (let i = 0; i < goodsLength; i++) {
      this.Buycarlist[shop_index]['goods_info'][i]['select'] = !isTrue;
      this.Buycarlist[shop_index]['goods_info'][i]['selectimg'] = imgUrl;
    }
  }

  /*
    
    传入一个店铺的 shop_index 遍历里面的子元素的select  如果都为true 的 父的select 为true   
  */
  checkServiceIndexByShopIndex(shop_index) {
    var a = this.Buycarlist[shop_index]['goods_info'].every((item) => { return item.select });
    /*所有都被选中*/
    if (a){
      this.selectAllByIndex({ shop_index, isTrue: false });
    }else{
      this.Buycarlist[shop_index]['select'] = false;
      this.Buycarlist[shop_index]['selectimg'] = 'assets/img/selectno1.png';
    } 
  }

  /**选择 商品的函数 以及全选按钮的函数 */
  selectCLI(shop_index, service_index) {
    /*
      shop_index:     表示点击的店铺在当前页面的编号
      service_index:  表示点击的服务在 被选中的店铺重的编号
    */
    console.log(shop_index, service_index);
    if (shop_index != null) {
      /*表示没有选择全选 按钮*/
      if (service_index == null) {
        /*表示选择了这个 店铺里面的所有的商品 */
        this.selectAllByIndex({ shop_index });
      } else {
        /*表示选择的是 这个店铺里面 一个 商品的index*/
        if (this.Buycarlist[shop_index]['goods_info'][service_index]['select']) {
          this.Buycarlist[shop_index]['goods_info'][service_index]['select'] = false;
          this.Buycarlist[shop_index]['goods_info'][service_index]['selectimg'] = 'assets/img/selectno1.png';
        } else {
          this.Buycarlist[shop_index]['goods_info'][service_index]['select'] = true;
          this.Buycarlist[shop_index]['goods_info'][service_index]['selectimg'] = 'assets/img/selectok.png';
        }
        this.checkServiceIndexByShopIndex(shop_index);
      }
    } else {
      this.showSelectImg = this.showSelectImg ? false : true;
      if (this.showSelectImg) {
        console.log("全部选择");
        for (let i = 0, length = this.Buycarlist.length; i < length; i++) {
          this.selectAllByIndex({ shop_index: i, isTrue: false });
        }
      } else {
        for (let i = 0, length = this.Buycarlist.length; i < length; i++) {
          this.selectAllByIndex({ shop_index: i, isTrue: true });
        }
      }
    }

    /*执行点击操作后 要验证 是否购物车里面的商品都被选中 */
    var isAll = this.Buycarlist.every((item) => { return item.select });
    // console.log(isAll);
    this.showSelectImg = isAll ? true : false;

    /*选择完之后要计算一下总价*/
    this.countAll();
  }

  /*删除购物车商品*/
  async check() {
    this.goodsID = [];
    this.param2.user_id = this.userinfo['user_id'];
    for (let item of this.selectAllArr) {
      for (let goods of item.goods_info) {
        this.goodsID.push(goods.id)
      }
    }
    console.log(this.goodsID)
    let goodsItem = this.goodsID.toString();
    this.param2.item_ids = goodsItem;
    console.log(this.param2);
    let result = await this.userService.cancelBuycarAPI(this.param2);
    console.log(result)
    if (result.code != 1) {
      this.showAlert(result.msg);
    } else {
      let toast = super.showToast(result.msg, 3000, "top")
      this.getmybuycar();
    }
  }
  /*  跳转到确认 购买 **/
  toOrderPage() {
    if (this.toHome == true) {
      this.choiceWay = true;
    } else {
      this.choiceWay = false;
    }
    if (this.Buycarlist == null) {
      this.showAlert("购物车没有商品哦，去首页转转吧");
      return;
    }
    this.navCtrl.push('OrderPage',
      { service_price: this.total, num: this.num, choice: this.choiceWay });
  }

  /*点击显示修改数量*/
  b(shopID) {
    console.log(shopID);
    this.change = false;
    this.shopID = shopID;
  }

  /**
   * 添加数量
   * @param i   该商品所属店铺的id
   * @param a   该商品的索引值，第几个商品
   */
  add(i, a) {
    let cart_id;
    let goods_num;
    console.log(i);//
    for (let j = 0; j < this.Buycarlist.length; j++) {
      if (this.Buycarlist[j].shop_id == i) {
        goods_num = ++this.Buycarlist[j].goods_info[a].goods_num;
        cart_id = this.Buycarlist[j].goods_info[a].id;
        console.log(goods_num)

      }
      this.countAll()
    }

    this.param3.user_id = this.userinfo['user_id'];
    this.param3.cart_id = cart_id;
    this.param3.goods_num = goods_num;

  }
  /**
   * 减少数量
   * @param i   该商品所属店铺的id
   * @param a   该商品的索引值，第几个商品
   */
  reduce(i, a, num) {
    if (num > 1) {
      let cart_id;
      let goods_num;
      console.log(i);//
      for (let j = 0; j < this.Buycarlist.length; j++) {
        if (this.Buycarlist[j].shop_id == i) {
          goods_num = --this.Buycarlist[j].goods_info[a].goods_num;
          cart_id = this.Buycarlist[j].goods_info[a].id;
          console.log(goods_num)

        }
        this.countAll()
      }

      this.param3.user_id = this.userinfo['user_id'];
      this.param3.cart_id = cart_id;
      this.param3.goods_num = goods_num;
    }

  }
  /*修改数量完成*/
  async complish() {
    this.change = true;
    console.log(this.param3);
    let result = await this.userService.changeCartNumAPI(this.param3);
    console.log(result)
    if (result.code == 1) {
      console.log("修改成功");
      let toast = this.toastCtrl.create({
        message: result.msg,
        duration: 3000,
      }).present();
    } else {
      console.log("修改失败");
      // let toast=this.toastCtrl.create({
      //   message:result.msg,
      //   duration:3000,
      // }).present();
      let toast = super.showToast(result.msg, 3000, 'top')
    }
    this.change = false;
    this.shopID = 0;
    this.countAll();
  }

}
